//
//  LoginViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ApplyLivingViewController.h"
#import "ForgetPasswordViewController.h"
#import "UserModel.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIImageView *LogoImageView;
@property (weak, nonatomic) IBOutlet UIButton *applyLivingBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIView *aplyTipView;

@end

@implementation LoginViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setOptions];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)setOptions {
    self.aplyTipView.hidden = YES;
    self.phoneNumTextField.keyboardType = UIKeyboardTypePhonePad;
    self.passwordTextField.secureTextEntry = YES;
    kButtonBorderRadius(self.applyLivingBtn, 5, 0.5, [UIColor textLightGrayColor]);
    self.loginBtn.titleEdgeInsets = UIEdgeInsetsMake(-12, 0, 0, 0);
    
}

#pragma mark --  直播申请
- (IBAction)LivingApply:(id)sender {
     self.aplyTipView.hidden = NO;
}

#pragma mark --  手机注册
- (IBAction)phoneRegister:(id)sender {
    RegisterViewController *registVc = [[RegisterViewController alloc] init];
    registVc.is_Sign = @"1";
    [self.navigationController pushViewController:registVc animated:YES];
    
}


#pragma mark --  忘记密码
- (IBAction)forgetPassword:(id)sender {
    RegisterViewController *registVc = [[RegisterViewController alloc] init];
    registVc.is_Sign = @"2";
    [self.navigationController pushViewController:registVc animated:YES];
}

#pragma mark --  登陆
- (IBAction)LoginClick:(id)sender {
    NSString *phoneNum = self.phoneNumTextField.text;
    NSString *password = self.passwordTextField.text;
    
    //先判断是否为空
    if ([phoneNum isEqualToString:@""]) {
        [self showTitle:@"请您输入手机号!"];
    } else if ([password isEqualToString:@""]) {
        [self showTitle:@"请您输入密码!"];
    } else {
        if ([self CheckPhoneNum:phoneNum]) {
            //验证账号密码 登录
            [self LoginRequestWithAccount:phoneNum PassWord:password];
        } else {
           [self showTitle:@"您输入的手机号或密码不正确!"];
        }
    }
}

// 检测手机号
- (BOOL)CheckPhoneNum:(NSString *)phoneNum {
    if ([self isValidateMobile:phoneNum]&&[self phoneNumDigitsisAvailableWithPhoneNum:phoneNum]) {
        return YES;
    } else {
        return NO;
    }

}

//判断手机号位数 以及是否可用
- (BOOL)phoneNumDigitsisAvailableWithPhoneNum:(NSString *)phoneNum {
    
    if (phoneNum.length == 11) {
        return YES;
    } else {
        return NO;
    }
    
}
-(BOOL)isValidateMobile:(NSString *)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

#pragma mark --  第三方登录 微信 QQ
- (IBAction)wechatLogin:(id)sender {
   [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession RegSource:@"20"];
}

- (IBAction)QQLogin:(id)sender {
    [self getUserInfoForPlatform:UMSocialPlatformType_QQ RegSource:@"10"];
}

#pragma mark -- 友盟第三方登陆
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType RegSource:(NSString *)source
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            //获取授权失败
            
        } else {
            NSLog(@"%@",result);
            UMSocialUserInfoResponse *userinfo =result;
            NSMutableDictionary *dict = (NSMutableDictionary *) userinfo.originalResponse;
            
            if ([source isEqualToString:@"10"]) {
                
//                NSString *name = dict[@"nickname"];
//                NSString *icon = dict[@"figureurl"];
//                NSString *openid = userinfo.openid;
                NSString *gender;
                if ([dict[@"gender"] isEqualToString:@"女"]) {
                    gender = @"2";
                } else if([dict[@"gender"] isEqualToString:@"男"]) {
                    gender = @"1";
                } else {
                    gender = @"0";//未知
                }
//QQ用户 qq授权信息 没有country(国家) region(区)
        [self SubmitUserInfoWithUserName:dict[@"nickname"]
                                  Source:source
                                    Icon:dict[@"figureurl"]
                                  Openid:userinfo.openid
                                  Gender:gender
                                 Country:@""
                                Province:dict[@"province"]
                                    City:dict[@"city"]
                                  Region:@""];
                
            } else if ([source isEqualToString:@"20"]) {
                //微信用户
                [self SubmitUserInfoWithUserName:dict[@"nickname"]
                                          Source:source
                                            Icon:dict[@"headimgurl"]
                                          Openid:dict[@"openid"]
                                          Gender:KString(dict[@"sex"])
                                         Country:dict[@"country"]
                                        Province:dict[@"province"]
                                            City:dict[@"city"]
                                          Region:@""];
            } else {
                //其他用户
            }
        }
        
    }];
}

#pragma mark -- 提交用户信息并注册
- (void)SubmitUserInfoWithUserName:(NSString *)name
                            Source:(NSString *)source
                              Icon:(NSString *)icon
                            Openid:(NSString *)openid
                            Gender:(NSString *)gender
                           Country:(NSString *)country
                          Province:(NSString *)province
                              City:(NSString *)city
                            Region:(NSString *)region {
    NSString *urlString = [TEST_URL stringByAppendingString:kThree_Login];
    NSDictionary *dicts = @{
                            @"name":name,
                            @"source":source,
                            @"icon":icon,
                            @"openid":openid,
                            @"gender":gender,
                            @"country":country,
                            @"province":province,
                            @"city":city,
                            @"region":region
                            };
    [self showHUDInView:self.view title:@"登录中..."];
    [NetworkTools postReqeustWithParams:dicts UrlString:urlString successBlock:^(id responseObject) {
        NSLog(@"成功");
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {//请求成功
            NSDictionary *userDic = responseObject[@"data"];
            NSString *tim = responseObject[@"data"][@"tim"];
            NSString *token = responseObject[@"token"];
            if ([[LSUserInfoManager sharedManager] didLoginInWithUserInfo:userDic]&&[LSFileCacheManager saveObject:token byFileName:kLOG_TOKEN]&&[LSFileCacheManager saveObject:tim byFileName:kIMUserSign]) { //存储信息成功
                NSString *userType = KString(userDic[@"u_type"]);
                QZHTabBarController *tabBar = [[QZHTabBarController alloc] initWithUserType:userType];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
            }
            
        } else if ([KString(responseObject[@"code"]) isEqualToString:@"400"]) {
            [self showTitle:responseObject[@"data"][@"message"]];
        }
        
    } failureBlock:^(NSError *error) {
        [self hideHUD];
        [self showTitle:@"连接服务器失败..."];
    } showHUD:NO];
}


#pragma mark --  账号登录 请求
- (void)LoginRequestWithAccount:(NSString *)account PassWord:(NSString *)password {
    NSDictionary *dict = @{
                           @"phone":account,
                           @"password":password
                           };
    [self showHUDInView:self.view title:@"登录中..."];
    NSString *urlString = [TEST_URL stringByAppendingString:kAccount_Login];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {//请求成功
            NSDictionary *userDic = responseObject[@"data"];
            NSString *tim = responseObject[@"data"][@"tim"];
            NSString *token = responseObject[@"token"];
            if ([[LSUserInfoManager sharedManager] didLoginInWithUserInfo:userDic]&&[LSFileCacheManager saveObject:token byFileName:kLOG_TOKEN]&&[LSFileCacheManager saveObject:tim byFileName:kIMUserSign]) { //存储信息成功
                NSString *userType = KString(userDic[@"u_type"]);
                QZHTabBarController *tabBar = [[QZHTabBarController alloc] initWithUserType:userType];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabBar;
            }
        } else if ([KString(responseObject[@"code"]) isEqualToString:@"400"]) {
            [self showTitle:responseObject[@"data"][@"message"]];
        } 
    } failureBlock:^(NSError *error) {
        [self hideHUD];
        [self showTitle:@"连接服务器错误..."];
    } showHUD:NO];
}


#pragma mark -- 点击空白 隐藏键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


#pragma mark -- 关闭提示
- (IBAction)closeTips:(id)sender {
    self.aplyTipView.hidden = YES;
}

#pragma mark -- 电话申请
- (IBAction)call:(id)sender {
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",@"15538864130"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --  UITextField Delegate


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
